package com.api.oa.services.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.api.oa.common.ToolUtils;
import com.api.oa.common.UserType;
import com.api.oa.config.EmServer;
import com.api.oa.config.UserContext;
import com.api.oa.exception.BadRequestException;
import com.api.oa.mapper.YQInsEntityMapper;
import com.api.oa.mapper.YQInsPatientHisMapper;
import com.api.oa.mapper.YQPatientMapper;
import com.api.oa.mapper.YQUserMapper;
import com.api.oa.model.entity.YQInsPatientHis;
import com.api.oa.model.entity.YQPatient;
import com.api.oa.model.entity.YQUser;
import com.api.oa.model.vo.YQMedCareVO;
import com.api.oa.model.vo.YQPatientVO;
import com.api.oa.services.YQPatientService;
import com.api.oa.utils.LocalRedis;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class YQPatientServiceImpl implements YQPatientService {

    @Autowired
    private YQPatientMapper mapper;

    @Autowired
    private YQUserMapper yqUserMapper;

    @Autowired
    private YQInsEntityMapper yqInsEntityMapper;
    @Autowired
    private YQInsPatientHisMapper yqInsPatientHisMapper;

    @Autowired
    private LocalRedis localRedis;


    @Override
    @Transactional
    public Integer add(YQPatient entity) throws BadRequestException {


        if (UserContext.getRole() == UserType.INS) {
            entity.setPatientIns(UserContext.getInsCode());
        }
        if (StrUtil.isEmpty(entity.getPatientIns())) {
            throw new BadRequestException("签约机构不能空");
        }
        if (StrUtil.isEmpty(entity.getPatientName())) {
            throw new BadRequestException("患者姓名不能空");
        }

        if (StrUtil.isEmpty(entity.getPatientIdCard()) || !IdcardUtil.isValidCard(entity.getPatientIdCard())) {
            throw new BadRequestException("身份证号不合法");
        }

        //判断机构是否已经存在 合法性，不存在 抛出异常
        Integer exit = yqInsEntityMapper.isExit(entity.getPatientIns());
        if (exit == 0) {
            throw new BadRequestException("机构编码不合法");
        }
        YQUser oneByIDCard = yqUserMapper.findOneByIDCard(entity.getPatientIdCard());
        if (oneByIDCard == null) {
            //注册一个用户
            YQUser yqUser = new YQUser();
            yqUser.setUserType(UserType.PATIENT); //患者
            yqUser.setCreatedAt(new Date());
            yqUser.setIdCard(entity.getPatientIdCard());
            yqUser.setStatus(0);
            yqUser.setUname(entity.getPatientName());
            yqUser.setBelongInsCode(entity.getPatientIns());
            yqUser.setPhone(entity.getPatientPhone());
            yqUser.setPasswd(SecureUtil.md5("123456"));
            yqUserMapper.insert(yqUser);
            String imUser = emServer.createImUser("a" + String.valueOf(yqUser.getUserId()), "123456", yqUser.getUname());
            yqUser.setEmUuid(imUser);
            //历史记录
            YQInsPatientHis yqInsPatientHis = new YQInsPatientHis();
            yqInsPatientHis.setPatientIdCard(entity.getPatientIdCard());
            yqInsPatientHis.setInsCode(entity.getPatientIns());
            yqInsPatientHis.setCreatedAt(DateUtil.date());
            yqInsPatientHisMapper.insert(yqInsPatientHis);
        } else {
            oneByIDCard.setBelongInsCode(entity.getPatientIns()); //所属机构编码
            oneByIDCard.setIdCard(entity.getPatientIdCard());
            oneByIDCard.setPhone(entity.getPatientPhone());
            oneByIDCard.setUname(entity.getPatientName());
            yqUserMapper.update(oneByIDCard);
        }
        return mapper.insert(entity);
    }

    @Override
    public void remove(String id) {
        mapper.delete(id);
    }

    @Override
    public Integer update(YQPatient entity) {
        return mapper.update(entity);
    }

    @Override
    public PageInfo<YQPatient> list(Long pid, Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("patientAddBed desc");
        return new PageInfo<>(mapper.list(pid));
    }

    @Override
    public PageInfo<YQPatientVO> page(String idCard, String insCode, String attendType, Integer pageIndex, Integer pageSize) {
        if (UserContext.getRole() == UserType.INS) {
            insCode = UserContext.getInsCode(); //只有机构 才会有值
        }
        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("patientAddBed desc,patientIdCard desc");
        return new PageInfo<>(mapper.page(idCard, insCode, attendType));
    }

    @Override
    public YQPatient one(Long id) {
        return mapper.findOne(id);
    }


    @Autowired
    EmServer emServer;


    @Override
    @Transactional
    public void addBatch(List<YQPatient> entities) throws BadRequestException {
        for (int i = 0; i < entities.size(); i++) {
            YQPatient yqPatient = entities.get(i);
//            if(StrUtil.isEmpty(yqPatient.getPatientPhone())){
//                throw new BadRequestException("手机号不能为空"+ yqPatient);
//            }
//            if(!PhoneUtil.isPhone(yqPatient.getPatientPhone())){
//                throw new BadRequestException("手机号不合法"+ yqPatient);
//            }
            if (StrUtil.isEmpty(yqPatient.getPatientIns())) {
                throw new BadRequestException("签约机构不能空" + yqPatient);
            }

            if (StrUtil.isEmpty(yqPatient.getPatientIdCard()) || !IdcardUtil.isValidCard(yqPatient.getPatientIdCard())) {
                throw new BadRequestException("身份证号不合法");
            }


        }
        if (entities.size() != entities.stream().map(YQPatient::getPatientIdCard).distinct().count()) {
            throw new BadRequestException("身份证有重复");
        }
        for (int i = 0; i < entities.size(); i++) {
            YQPatient yqPatient = entities.get(i);
            //判断机构是否已经存在 合法性，不存在 抛出异常
            Integer exit = yqInsEntityMapper.isExit(yqPatient.getPatientIns());
            if (exit == 0) {
                continue;
            }
            YQPatient oneByPhone = mapper.findOneByIdCard(yqPatient.getPatientIdCard());
            if (oneByPhone == null) {
                mapper.insert(yqPatient);
                //注册一个用户
            } else {
                mapper.update(yqPatient);
            }
            YQUser oneByIDCard = yqUserMapper.findOneByIDCard(yqPatient.getPatientIdCard());
            if (oneByIDCard == null) {
                YQUser yqUser = new YQUser();
                yqUser.setUserType(UserType.PATIENT); //患者
                yqUser.setCreatedAt(new Date());
                yqUser.setIdCard(yqPatient.getPatientIdCard());
                yqUser.setStatus(0);
                yqUser.setUname(yqPatient.getPatientName());
                yqUser.setBelongInsCode(yqPatient.getPatientIns());
                yqUser.setPhone(yqPatient.getPatientPhone());
                yqUser.setPasswd(SecureUtil.md5("123456"));
                yqUserMapper.insert(yqUser);

                String imUser = emServer.createImUser("a" + String.valueOf(yqUser.getUserId()), "123456", yqUser.getUname());
                yqUser.setEmUuid(imUser);

                YQInsPatientHis yqInsPatientHis = new YQInsPatientHis();
                yqInsPatientHis.setPatientIdCard(yqPatient.getPatientIdCard());
                yqInsPatientHis.setInsCode(yqPatient.getPatientIns());
                yqInsPatientHis.setCreatedAt(DateUtil.date());
                yqInsPatientHisMapper.insert(yqInsPatientHis);
            } else {
                oneByIDCard.setBelongInsCode(yqPatient.getPatientIns()); //所属机构编码
                oneByIDCard.setIdCard(yqPatient.getPatientIdCard());
                oneByIDCard.setPhone(yqPatient.getPatientPhone());
                yqUserMapper.updateUser(oneByIDCard);
            }
        }
    }

    @Override
    public PageInfo<YQPatientVO> patientByIns(Long userId, String keyWord, Integer pageIndex, Integer pageSize) {
        YQUser one = yqUserMapper.findOne(userId);
        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("patientAddBed desc,patientIdCard desc");
        return new PageInfo<>(mapper.pageByIns(one.getBelongInsCode(), "1", keyWord)); //院护
    }

    @Override
    public List<YQPatientVO> allPatient(String insCode) {
        if (UserContext.getRole() == UserType.INS) {
            insCode = UserContext.getInsCode();
        }
        String key = String.format("YQPatientService.%s", insCode == null ? "all" : insCode);
        Object o = localRedis.get(key);
        if (o == null) {
            List<YQPatientVO> yqPatientVOS = mapper.allPatient(insCode);
            localRedis.set(key, yqPatientVOS, 3600 * 24 * 5);
            return yqPatientVOS;
        }
        return (List<YQPatientVO>) o;
    }

    @Override
    public void export(String idCard, String insCode, String attendType, Integer pageIndex, Integer pageSize, HttpServletResponse res) throws IOException {
        List<YQPatientVO> page = mapper.page(idCard, insCode, attendType);
        List<Map<String, Object>> collect = page.stream().map(i -> {
            Map<String, Object> map = new HashMap<>();
            map.put("手机号", i.getInsName());
            map.put("身份证", i.getPatientIdCard());
            map.put("姓名", i.getPatientName());
            map.put("性别", i.getPatientSex());
            map.put("照片", i.getPatientFace());
            map.put("人员身份", i.getIdCardType());
            map.put("经度", i.getLat());
            map.put("纬度", i.getLng());
            map.put("签约机构", i.getPatientIns());
            map.put("建床时间", i.getPatientAddBed());
            map.put("类型", i.getPatientType());
            map.put("等级", i.getPatientLevel());
            map.put("护理类型", i.getAttendType());
            map.put("禁用", i.getDisabled());
            map.put("病情描述", i.getConditionDesc());
            map.put("机构名称", i.getInsName());
            return map;
        }).collect(Collectors.toList());
        ToolUtils.downLoadExcel(collect, res);
    }
}


